<?php

namespace App\Http\Controllers\Admin;

use Validator;
use App\Category;
use App\ShowPosition;
use App\PositionData;
use Illuminate\Http\Request;
use App\MyTools\ThumbnailImage;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    public function index(Request $request)
    {
        $categories = Category::orderBy('fullpath', 'asc')->get();
        return view('admin.category.index', [
            'request' => $request,
            'categories' => $categories
        ]);
    }

    public function add(Request $request, ThumbnailImage $img)
    {
        if ($request->isMethod('post')) {
            $data = $request->except(['_token']);
            $rules = [
                'name' => 'required',
                'type' => 'in:0,1',
                'is_nav' => 'in:0,1'
            ];
            $messages = [
                'name.required' => '请输入栏目名！',
                'type.in' => '请选择栏目类型！',
                'is_nav.in' =>'请选择是否显示！'
            ];
            if ($data['type'] == '1') {
                $rules['content'] = 'required';
                $messages['content.required'] = '请输入栏目内容！';
            }
            $validator = Validator::make($data, $rules, $messages);
            if ($validator->fails()) {
                $return = [
                    'status' => 'n',
                    'info' => $validator->errors()->first()
                ];
                return response()->json($return);
            }
            $datas = [
                'name' => $data['name'],
                'type' => $data['type'],
                'sort' => $data['sort']
            ];
            if ($data['type'] == '0') {
                $datas['parent_id'] = $data['parent_id'];
            } elseif ($data['type'] == '1') {
                $datas['parent_id'] = 0;
            }
            if (!empty($data['content'])) {
                $datas['content'] = $data['content'];
            }
            if (!empty($data['thumbnail'])) {
                $srcImg = 'upload/' . $data['thumbnail'];
                $dstName = pathinfo($data['thumbnail'], PATHINFO_FILENAME) .
                    '_thumbnail' . '.' . pathinfo($data['thumbnail'], PATHINFO_EXTENSION);
                $dstImg = 'upload/' . $dstName;
                $datas['thumbnail'] = $data['thumbnail'];
                $datas['thumbnail_s'] = $dstName;
                $imgResult = $img->img2thumb($srcImg, $dstImg, 0, 0, 0, 0.5);
                if (!$imgResult) {
                    $return = ['status' => 'n', 'info' => '缩略图生成失败，请稍候重试！'];
                    return response()->json($return);
                }
            }
            if (!empty($data['route'])) {
                $datas['route'] = $data['route'];
            }
            $result = Category::create($datas);
            if (!isset($result->id)) {
                $return = ['status' => 'n', 'info' => '请稍候重试！'];
                return response()->json($return);
            }
            if (isset($data['position'])) {
                foreach ($data['position'] as $val) {
                    $positionData = new PositionData();
                    $positionData->position_id = $val;
                    $positionData->category_id = $result->id;
                    if (!$positionData->save()) {
                        $return = ['status' => 'n', 'info' => '请稍候重试！'];
                        return response()->json($return);
                    }
                }
            }
            if ($data['parent_id'] == '0') {
                $result->fullpath = $result->id;
            } else {
                $parentCategory = Category::find($data['parent_id']);
                $result->fullpath = $parentCategory->fullpath . ',' . $result->id;
            }
            if ($result->save()) {
                $return = ['status' => 'y'];
                return response()->json($return);
            } else {
                $return = ['status' => 'n', 'info' => '请稍候重试！'];
                return response()->json($return);
            }
        }
        $categories = Category::orderBy('fullpath', 'asc')
            ->where('type', '0')->get();
        $showPositions = ShowPosition::get();
        return view('admin.category.add', [
            'request' => $request,
            'categories' => $categories,
            'showPositions' => $showPositions
        ]);
    }

    public function edit(Request $request, $id, ThumbnailImage $img)
    {
        if ($request->isMethod('post')) {
            $data = $request->except(['_token']);
            $rules = [
                'name' => 'required',
                'type' => 'in:0,1',
                'is_nav' => 'in:0,1'
            ];
            $messages = [
                'name.required' => '请输入栏目名！',
                'type.in' => '请选择栏目类型！',
                'is_nav.in' =>'请选择是否显示！'
            ];
            $validator = Validator::make($data, $rules, $messages);
            if ($validator->fails()) {
                $return = [
                    'status' => 'n',
                    'info' => $validator->errors()->first()
                ];
                return response()->json($return);
            }
            $category = Category::find($data['id']);
            if (isset($data['position'])) {
                PositionData::where('category_id', $category->id)->delete();
                foreach ($data['position'] as $val) {
                    $positionData = new PositionData();
                    $positionData->position_id = $val;
                    $positionData->category_id = $category->id;
                    if (!$positionData->save()) {
                        $return = ['status' => 'n', 'info' => '请稍候重试！'];
                        return response()->json($return);
                    }
                }
            } else {
                PositionData::where('category_id', $category->id)->delete();
            }
            if ($category->type == '0'
                && $category->parent_id != $data['parent_id']) {
                $category->parent_id = $data['parent_id'];
                $parentCategory = Category::find($data['parent_id']);
                $category->fullpath = $parentCategory->fullpath . ','
                    . $category->id;
            }
            if (!empty($data['thumbnail'])) {
                $thumbnail = 'upload/' . $category->thumbnail;
                $thumbnailS = 'upload/' . $category->thumbnail_s;
                if (is_file($thumbnail)) {
                    unlink($thumbnail);
                }
                if (is_file($thumbnailS)) {
                    unlink($thumbnailS);
                }
                $srcImg = 'upload/' . $data['thumbnail'];
                $dstName = pathinfo($data['thumbnail'], PATHINFO_FILENAME) .
                    '_thumbnail' . '.'
                    . pathinfo($data['thumbnail'], PATHINFO_EXTENSION);
                $dstImg = 'upload/' . $dstName;
                $category->thumbnail = $data['thumbnail'];
                $category->thumbnail_s = $dstName;
                $imgResult = $img->img2thumb($srcImg, $dstImg, 0, 0, 0, 0.5);
                if (!$imgResult) {
                    $return = ['status' => 'n', 'info' => '缩略图生成失败，请稍候重试！'];
                    return response()->json($return);
                }
            }
            if (!empty($data['route'])) {
                $category->route = $data['route'];
            }
            $category->name = $data['name'];
            $category->sort = $data['sort'];
            $category->save();
            $return = ['status' => 'y'];
            return response()->json($return);
        }
        $categories = Category::orderBy('fullpath', 'asc')
            ->where([
                ['id', '!=', $id],
                ['type', '=', '0']
            ])->get();
        $thisCategory = Category::find($id);
        $showPositions = ShowPosition::get();
        $categoryPositions = PositionData::where('category_id', $thisCategory->id)
            ->get();
        foreach ($showPositions as $showPosition) {
            $showPosition->isChecked = false;
            foreach ($categoryPositions as $categoryPosition) {
                if ($showPosition->id == $categoryPosition->position_id) {
                    $showPosition->isChecked = true;
                    break;
                }
            }
        }
        return view('admin.category.edit', [
            'request' => $request,
            'categories' => $categories,
            'thisCategory' => $thisCategory,
            'showPositions' => $showPositions
        ]);
    }

    public function del(Request $request)
    {
        $id = $request->input('id');
        $category = Category::find($id);
        $thumbnail = 'upload/' . $category->thumbnail;
        $thumbnailS = 'upload/' . $category->thumbnail_s;
        if (is_file($thumbnail)) {
            unlink($thumbnail);
        }
        if (is_file($thumbnailS)) {
            unlink($thumbnailS);
        }
        if ($category->delete()) {
            $return = ['status' => 'y'];
        } else {
            $return = ['status' => 'n', 'info' => '请稍候重试！'];
        }
        return response()->json($return);
    }
}